﻿using Castle.Core.Logging;
using IoTSocket.Core;
using IoTSocket.Sockets;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.VisualBasic;
using Opc.Ua;
using Polly;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using UaClient;
using Warehouse.Services.Repository;
using WCS.Entities;
using WCS.Entities.Api;
using static Org.BouncyCastle.Math.EC.ECCurve;
using TcpClient = IoTSocket.Sockets.TcpClient;

namespace WCS.Services
{
    /// <summary>
    /// TCP服务监听扫码上传
    /// </summary>
    public class TcpClientReadCode :BackgroundService
    {
        public static Dictionary<string, string> CodeMessage = new Dictionary<string, string>();

        public Dictionary<string,TcpClient> clients=new Dictionary<string, TcpClient> ();

        private readonly ILogger<TcpClientReadCode> logger;

		// { "10.6.6.10", "10.6.6.8"};
		private List<string> Ips = new List<string>() { /*"10.6.6.10",*//* "10.6.6.8"*/ };

        public TcpClientReadCode(ILogger<TcpClientReadCode> logger)
        {
            this.logger = logger;
          

        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while(!stoppingToken.IsCancellationRequested)
            {
                foreach (var ip in Ips)
                {
                     if(clients.ContainsKey(ip))
                    {
                        var client = clients[ip];

                        if(!client.Online)
                        {
                            clients[ip] = Connect(ip);
                        }
                    }
                     else
                    {
                        clients.Add(ip, Connect(ip));
                    }
                }

                await Task.Delay (1000);
            }

        }


        private TcpClient Connect(string ip)
        {
            TcpClient client = new TcpClient();
            client.Connected += Client_Connected;
            client.Disconnected += Client_Disconnected;
            client.Received += Client_Received;
            client.Setup($"{ip}:51236");
            client.Connect();
            return client;

        }
			

        private void Client_Disconnected(ITcpClientBase client, DisconnectEventArgs e)
        {
            logger.LogInformation("The Client {0} has  disconncted!", client.IP);
        }

        private void Client_Connected(ITcpClient client, MsgEventArgs e)
        {
            logger.LogInformation("The Client {0} has  conncted!", client.IP);
        }

        private void Client_Received(TcpClient client, ByteBlock byteBlock, IRequestInfo requestInfo)
        {
            string msg = Encoding.UTF8.GetString(byteBlock.Buffer, 0, byteBlock.Len);

            logger.LogInformation("Receive the client {0} message is:{1}", client.IP, msg);

            if(!string.IsNullOrEmpty(msg))
            {
                CodeMessage[client.IP]=msg;
            }
        }
    }


}
